/***2025-02-18 迷途小羔羊
* 用于编写加载的资源解析
*/
namespace GYLite
{
    export class ResParser
    {
        private static fontLoadingDict:any= {};
        /**文件字节数据解析*/
        public static bytesParse(l:SeqLoader|SeqURLLoader):GYLite.ResObject
        {
            let resObj:ResObject;
            var loadInfo:GYLite.LoadInfo;
            let loadType:LoadType;			
			loadInfo = l.loadInfo;
            loadType = loadInfo.type	
            resObj = ResObject.create();
            if(loadType == LoadType.TYPE_FONT)
            { 
                const blob = new Blob([l.data], { type: 'application/octet-stream' });           
                let arr:string[] = loadInfo.path.split(/\/|\\/g);
                let name:string;
                name = arr[arr.length - 1].split(".")[0];
                const font = new FontFace(name, l.data);
                ResParser.fontLoadingDict[name] = {data:blob, name:name, path:loadInfo.path};
                font.load().then(() => {
                    let obj:any = ResParser.fontLoadingDict[name];
                    delete ResParser.fontLoadingDict[name];
                    //先判断一下，加载是否已经过期
                    if(resObj.pathKey != obj.path)
                        return;
                    // 字体加载成功后，创建一个 style 元素并插入 @font-face 规则                    
                    resObj.res = ResParser.createFontStyle(obj.name,obj.data);
                }).catch(error => {
                    let obj:any = ResParser.fontLoadingDict[name];
                    delete ResParser.fontLoadingDict[obj.name];
                    new Error(`Font ${obj.name} failed to load: ${error.message}`);
                });                
            }
            else if(loadType == LoadType.TYPE_SOUND)
            {
                let winURL = window["URL"] || window["webkitURL"];
                resObj.res = winURL.createObjectURL(l.data);
            }            
            else if(loadType == LoadType.TYPE_JSON && CommonUtil.GYIs(l.data, String))
                resObj.res = JSON.parse(l.data);
            else
                resObj.res=l.data;	            
            
            resObj.pathKey = loadInfo.path;
            resObj.type = loadType;
            resObj.lifeTime = loadInfo.lifeTime;
            
            return resObj;
        }
        /**资源文件解析(网页多媒体加载器加载的内容，如Image、Audio)*/
        public static resParse(l:SeqLoader|SeqURLLoader):GYLite.ResObject
        {
            let resObj:ResObject;
            var loadInfo:GYLite.LoadInfo;
            let loadType:LoadType;			
			loadInfo = l.loadInfo;
            loadType = loadInfo.type			            
            if(loadType == LoadType.TYPE_ATLAS)
            {
                let result:{atlas:Atlas,atlasRect:AtlasRect,error:SysError};
				result = AtlasRender.getInstance().createAtlas(l.data.width,l.data.height,l.loadInfo.path,l.data,false);	
				if(result.error)				
					console.error(result.error.msg);
				resObj = result.atlas.atlasRes;				
				resObj.res = new egret.Texture();						
				(<egret.Texture>resObj.res).bitmapData = l.data;
            }
            else
            {
                resObj = ResObject.create();
                if(loadType == LoadType.TYPE_IMAGE || loadType == LoadType.TYPE_TEX || loadType == LoadType.TYPE_SPINE)
                {
                    let tex:egret.Texture = resObj.res = new egret.Texture();
                    tex.bitmapData = l.data;					
                    tex.bitmapData.$deleteSource = false;
                    if(GYLoader.imageToGPU)//直接上传到gpu
                        GYLite.GYSprite.stage.$displayList.renderBuffer.context.getWebGLTexture(tex.bitmapData)
                }
                else
                    resObj.res=l.data;
            }
            resObj.pathKey = loadInfo.path;
            resObj.type = loadType;
            resObj.lifeTime = loadInfo.lifeTime;
            
            return resObj;
        }
        public static createFontStyle(name:string, data:Blob):HTMLStyleElement 
        {
            const style = document.createElement('style');
            style.type = 'text/css';
            style.dataset.src = URL.createObjectURL(data);
            style.appendChild(document.createTextNode(`
                @font-face {
                    font-family: '${name}';
                    src: url(${style.dataset.src}) format('truetype');
                }
                div, canvas {
                    font-family: "${name}";
                }
            `));
            document.head.appendChild(style); 
            return style;
        }        
    }
}